package sqlhelper

import (
	"fmt"
	"strconv"
	"strings"
)

// 基于gorm where 查询

type CondItem struct {
	Field string
	Oper  string
	Value any // int 或者 string
}

func WhereCond(field string, val any, opers ...string) *CondItem {
	op := ""
	if len(opers) == 0 {
		op = "="
	} else {
		op = opers[0]
	}
	return &CondItem{Field: field, Oper: op, Value: val}
}

type Where struct {
	Conds   []*CondItem
	Formula string // {1} AND {2}
	Offset  int
	Limit   int
	Order   string
	Group   string
	query   string
	values  []any
}

func (this *Where) Do() *Where {
	if this.values == nil {
		this.values = []any{}
	}
	if len(this.Conds) > 0 && len(this.Formula) == 0 {
		this.Formula = "{1}"
	}
	for i, cond := range this.Conds {
		item_str := fmt.Sprintf(" %s %s ?", Camel2Case(cond.Field), cond.Oper)
		//fmt.Println("----", item_str)
		this.query = strings.ReplaceAll(this.Formula, "{"+strconv.Itoa(i+1)+"}", item_str)
		this.values = append(this.values, cond.Value)
	}
	return this
}

func (this *Where) Query() string {
	return this.query
}

func (this *Where) Values() []any {
	return this.values
}

//

func Camel2Case(field string) string {
	return field
	//// 特殊字段
	//field = strings.ReplaceAll(field, "UUID", "uuid")
	//// 局部 包含
	//field = strings.ReplaceAll(field, "ID", "Id")
	//
	////fmt.Println("--------------", field)
	//return helper.Camel2Case(field)
}
